//
//  SongerListViewController.m
//  DayByDay
//
//  Created by dllo on 16/5/20.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "SongerListViewController.h"
#import <AFNetworking.h>
#import "SongerListDataModel.h"
#import "SongerListTableViewCell.h"
#import "SongListDetailViewController.h"

@interface SongerListViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate>

//@property (nonatomic, strong)UICollectionView *collectionView;
@property (nonatomic, strong)NSMutableArray *array;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SongerListDataModel *dataModel;

// 搜索专用



@property(nonatomic,retain)NSMutableArray *searchArray;


@property(nonatomic,retain)UISearchBar *mySearchBar;
@property(nonatomic,retain)UISearchDisplayController *searchDC;
@property(nonatomic,retain)UISearchController *searchController;


@end

@implementation SongerListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.searchArray = [NSMutableArray array];
    [self createData];
    [self createView];
    [self createSearchVC];
}

- (void)createSearchVC {
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    self.searchController.searchResultsUpdater = self;
    //    设置开始搜索时背景显示与否 页面背景阴影效果,一般不要设置.
    self.searchController.dimsBackgroundDuringPresentation = NO;
    //设置点击搜索框时候隐藏导航栏
    self.searchController.hidesNavigationBarDuringPresentation = NO;
    self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
    //    [searchBar sizeToFit]:设置searchBar位置自适应
    [self.searchController.searchBar sizeToFit];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    //    self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //    [self.HUB show:YES];
}



- (void)createData {
    NSString *firstStr = @"http://api.dongting.com/song/singer_classify/";
    NSString *lastStr = @"?app=ttpod&v=v9.0.1.2016050614&user_id=0&mid=iPhone7%2C2&f=f320&s=s310&imsi=&hid=&splus=9.3.1&active=1&net=2&openudid=5e6106cc8d5bcf35f60a2997c79a00bb5a7c631f&idfa=ABDADD65-0877-4840-B14F-DFC8D1114AB0&utdid=VzR0dwnWYs8DANbYJ8SsFzOU&alf=(null)&bundle_id=com.ttpod.music&latitude=-1&longtitude=-1&access_token=(null)&vc=9000100";
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@",firstStr,self.songerId,lastStr];
//    NSString *encodeString = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSLog(@"%@",urlStr);
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
//    NSURL *url = [NSURL URLWithString:urlStr];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionDataTask *downloadTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        dispatch_queue_t mainQueue = dispatch_get_main_queue();
//        dispatch_async(mainQueue, ^{
//            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//            for (NSDictionary *Sdic in [dic valueForKey:@"data"]) {
//                self.dataModel = [SongerListDataModel new];
//                [self.dataModel setValuesForKeysWithDictionary:Sdic];
//            }
//            NSLog(@"%@",dic);
//            [self.tableView reloadData];
//        });
//    }];
//    [downloadTask resume];
    
//    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript", nil]];
//    
//    [manager GET:encodeString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        self.dataModel = [SongerListDataModel new];
//        [self.dataModel setValuesForKeysWithDictionary:[responseObject objectForKey:@"data"]];
//        [self.tableView reloadData];
//        NSLog(@"%@'",responseObject);
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
//        
//    }];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSURLSessionConfiguration *configur = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configur];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            self.dataModel = [SongerListDataModel new];
            [self.dataModel setValuesForKeysWithDictionary:[dic objectForKey:@"data"]];
            [self.tableView reloadData];
        });
    }];
    [task resume];
}

- (void)createView {
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[SongerListTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SongerListTableViewCell class])];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SongerListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SongerListTableViewCell class])];
    SongerListDataListModel *model = nil;
    if (self.searchController.active) {
        
//        NSLog(@"选中搜索列表");
        model = [self.searchArray objectAtIndex:indexPath.row];
        
    }
    else {
        
//        NSLog(@"选中所有列表");
        model = self.dataModel.singers[indexPath.row];
        
    }

//    SongerListDataListModel *model = self.dataModel.singers[indexPath.row];
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.searchController.active) {
        
        return self.searchArray.count;
        
    }
    else {
        
//        NSLog(@"选中所有列表");
        return self.dataModel.singers.count;
        
    }
//    return self.dataModel.singers.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SongListDetailViewController *songVC = [SongListDetailViewController new];
    SongerListDataListModel *model = nil;
    if (self.searchController.active) {
        
//        NSLog(@"选中搜索列表");
        model = [self.searchArray objectAtIndex:indexPath.row];
        songVC.value = [model.singerId stringValue];
        
    }
    else {
        
//        NSLog(@"选中所有列表");
//        model = self.dataModel.singers[indexPath.row];
        songVC.value = [[self.dataModel.singers[indexPath.row] singerId] stringValue];
        
    }

//    songVC.value = [[self.dataModel.singers[indexPath.row] singerId] stringValue];
    [self.navigationController pushViewController:songVC animated:YES];
}


-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    
    NSString *searchString = [self.searchController.searchBar text];
    
//    NSLog(@"===%@",searchString);
    
    [self.searchArray removeAllObjects];
    
    for (SongerListDataListModel *model in self.dataModel.singers) {
//        NSLog(@"%@",model.name);
        //rangeOfString:方法是在model中搜索是否包含searchText
        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
        //NSNotFound 表示请求操作的某个内容没有发现
        if ([model.name rangeOfString:searchString].location != NSNotFound) {
            
            [self.searchArray addObject:model];
        }
    }
//    NSLog(@"searchArray===%@",self.searchArray);
    
    [self.tableView reloadData];
    
}

//UISearchController的移除
//在viewWillDisappear中要将UISearchController移除, 否则切换到下一个View中, 搜索框仍然会有短暂的存在.
- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.searchController.active) {
        
        self.searchController.active = NO;
        [self.searchController.searchBar removeFromSuperview];
        
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
